package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.Setmeal;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.ISetmealService;
import com.itheima.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public Result getSetmeal(Long id) {
        //根据id查找套餐
        Setmeal setmeal = setmealMapper.selectById(id);
        //判断是否存在
        if (setmeal == null) {
            return Result.error("不存在");
        }
        return Result.success(setmeal);
    }

    @Override
    public Result status(Integer status, Long ids) {
        //根据id查找套餐
        Setmeal setmeal = setmealMapper.selectById(ids);
        //判断套餐是否存在
        if (setmeal == null) {
            return Result.error("该套餐不存在");
        }
        setmeal.setStatus(status);
        int r = setmealMapper.updateById(setmeal);
        //判断是否修改成功
        if (r<=0){
            return Result.error("修改失败");
        }
        return Result.success(setmeal);
    }

    @Override
    public Result setmealList(Long categoryId, Integer status) {
        //判断当前的套餐时候售卖
        if (status==0){
            return Result.error("当前套餐下架");
        }
        //根据套餐的id，查询下面的子套餐
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Setmeal::getCategoryId,categoryId);
        List<Setmeal> setmealList = setmealMapper.selectList(lqw);
        return Result.success(setmealList);
    }

    @Override
    public IPage<Setmeal> getPage(int current, int pageSize, String name) {
        if (name != null){
            LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Setmeal::getName,name);
            IPage<Setmeal> page = new Page<Setmeal>(current,pageSize);
            return setmealMapper.selectPage(page,lqw);
        }
        IPage<Setmeal> page = new Page<Setmeal>(current,pageSize);
        return setmealMapper.selectPage(page,null);
    }
}
